﻿using UnityEngine;
using SLua;

public class LuaBehaviour : MonoBehaviour
{
    public string luaClass;
    private bool _init;

    private LuaState L { get { return LuaState.main; } }

    private LuaTable _luaModule;
    public LuaTable LuaModule
    {
        get
        {
            if (_luaModule == null)
            {
                Initilize(luaClass);
            }
            return _luaModule;
        }
        private set { _luaModule = value; }
    }

    public static LuaTable GetLuaComponent(GameObject go)
    {
        LuaBehaviour luaComp = go.GetComponent<LuaBehaviour>();
        if (luaComp == null)
            return null;
        return luaComp.LuaModule;
    }

    public void Initilize(string fileName)
    {
        if (_init) return;
        if (string.IsNullOrEmpty(fileName)) return;
        RunLuaFile("game.module.ui.component." + fileName);
        LuaModule["gameObject"] = gameObject;
        LuaModule["transform"] = transform;
        CallLuaFunction("Awake");
        _init = true;
    }

    /// <summary>
    /// 调用Lua虚拟机，执行一个脚本文件
    /// </summary>
    void RunLuaFile(string fileName)
    {
        if (string.IsNullOrEmpty(fileName))
            return;

        object luaRet = L.doFile(fileName);

        if (luaRet == null)
        {
            Debuger.LogError("Lua脚本错误或无返回对象: " + fileName);
        }
        else
        {
            LuaModule = luaRet as LuaTable;
        }
    }

    /// <summary>
    /// 调用Lua组件中的函数
    /// </summary>
    void CallLuaFunction(string funcName, params object[] args)
    {
        if (L == null)
        {
            return;
        }
        if (_luaModule == null)
            return;

        LuaFunction func = _luaModule[funcName] as LuaFunction;

        if (func != null)
            func.call(args);
    }
}
